package com.programmercarl.string;

import java.util.Arrays;

/**
 * https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/description/
 * KMP算法
 *
 * @author yulongtian
 * @create 2024-12-15 13:09
 */
public class Test06 {
    public static void main(String[] args) {

//
        System.out.println(Arrays.toString(getNext("ABACABAB")));
//        System.out.println(strStr("leetcode", "leeto"));
    }

    public static int strStr(String haystack, String needle) {
        int[] next = getNext(needle);
        int i = 0;
        int j = 0;
        while (i < haystack.length()) {
            if (haystack.charAt(i) == needle.charAt(j)) {
                i++;
                j++;
            } else if (j > 0) {
                j = next[j - 1];
            } else {
                i++;
            }
            if (j == needle.length()) {
                return i - j;
            }
        }

        return -1;
    }

    public static int[] getNext(String haystack) {
        int[] next = new int[haystack.length()];
        int prefix_len = 0;
        int i = 1;
        while (i < haystack.length()) {
            if (haystack.charAt(prefix_len) == haystack.charAt(i)) {
                prefix_len++;
                next[i] = prefix_len;
                i++;
            } else {
                if (prefix_len == 0) {
                    i++;
                } else {
                    prefix_len = next[prefix_len - 1];
                }
            }
        }
        return next;
    }

    /**
     * 不行
     *
     * @param haystack
     * @param needle
     * @return
     */
    public static int strStr1(String haystack, String needle) {
        if (haystack.length() < needle.length()) {
            return -1;
        }
        for (int i = 0; i < haystack.length(); i++) {
            if (haystack.charAt(i) != needle.charAt(0)) {
                continue;
            }
            int j = 0;
            for (; j < needle.length() && i + j < haystack.length(); j++) {
                if (haystack.charAt(i + j) != needle.charAt(j)) {
                    break;
                }
            }
            if (j == needle.length()) {
                return i;
            }
        }
        return -1;
    }
}
